<template>
    <view>
        <checkbox-group @change="bindChange" class="checkbox-group">
            <view class="item" v-for="(item, index) in sourceData" :key="index">
                <label>
                    <checkbox :disabled="disabled" :value="item" :checked="tools.includes(itemMulti, item)" />
                    <text>{{ item }}</text>
                </label>
            </view>
        </checkbox-group>
    </view>
</template>
<script module="tools" lang="wxs" src="@/tpls/wxs/tools.wxs"></script>
<script>
export default {
    data() {
        return {};
    },
    externalClasses: ['outside-picker-multi-class'],
    /**
     * 组件的属性列表
     */
    props: {
        sourceData: {
            //源数组
            type: Array,
            default: () => []
        },
        // 默认选中项的值数组
        itemMulti: {
            type: Array,
            default: () => []
        },
        disabled: {
            // 是否禁用
            type: Boolean,
            default: false
        }
    },
    mounted() {
        // 处理小程序 attached 生命周期
        this.attached();
        // 处理小程序 ready 生命周期
        this.$nextTick(() => this.ready());
    },
    destroyed: function () {
        // 在组件实例被从页面节点树移除时执行
    },
    /**
     * 组件的方法列表
     */
    methods: {
        ready: function () {
            this.fixDefaultValFun();
        },

        attached: function () {},

        bindChange: function (e) {
            this.$emit('select', {
                detail: e.detail.value
            });
        },

        fixDefaultValFun() {
            //传入数据不匹配的时候，修正父页面传入的的数组默认值
            if (!Array.isArray(this.itemMulti)) {
                this.$emit('select', {
                    detail: []
                });
            }
            if (this.itemMulti.length == 0) {
                return;
            }
            let ret = [];
            let sourceData = this.sourceData;
            let itemMulti = this.itemMulti;
            for (let k in sourceData) {
                for (let j in itemMulti) {
                    if (sourceData[k] == itemMulti[j]) {
                        ret.push(itemMulti[j]);
                    }
                }
            }
            this.$emit('select', {
                detail: ret
            });
        }
    },
    created: function () {},
    watch: {
        itemMulti: {
            handler: function (newVal, oldVal) {
                if (JSON.stringify(newVal) != JSON.stringify(oldVal)) {
                    console.log('checkbox observer');
                    this.fixDefaultValFun();
                }
            },

            immediate: true,
            deep: true
        }
    }
};
</script>
<style>
@import './checkbox_cmpt.css';
</style>
